TODO: Add validations to create user form
This commit is contained in:
+2
-2
@@ -1,6 +1,6 @@
|
||||
package com.adityachandel.booklore.config.security;
|
||||
|
||||
import com.adityachandel.booklore.model.entity.UserEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookLoreUserEntity;
|
||||
import com.adityachandel.booklore.model.entity.UserPermissionsEntity;
|
||||
import com.adityachandel.booklore.repository.UserRepository;
|
||||
import lombok.AllArgsConstructor;
|
||||
@@ -20,7 +20,7 @@ public class ApplicationStartupRunner implements CommandLineRunner {
|
||||
@Override
|
||||
public void run(String... args) {
|
||||
if (userRepository.findByUsername("admin").isEmpty()) {
|
||||
UserEntity admin = new UserEntity();
|
||||
BookLoreUserEntity admin = new BookLoreUserEntity();
|
||||
admin.setUsername("admin");
|
||||
admin.setPasswordHash(passwordEncoder.encode("admin123"));
|
||||
admin.setName("Administrator");
|
||||
|
||||
+3
-3
@@ -1,6 +1,6 @@
|
||||
package com.adityachandel.booklore.config.security;
|
||||
|
||||
import com.adityachandel.booklore.model.entity.UserEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookLoreUserEntity;
|
||||
import com.adityachandel.booklore.model.entity.UserPermissionsEntity;
|
||||
import com.adityachandel.booklore.repository.UserRepository;
|
||||
import jakarta.servlet.FilterChain;
|
||||
@@ -39,8 +39,8 @@ public class JwtAuthenticationFilter extends OncePerRequestFilter {
|
||||
|
||||
if (token != null && jwtUtils.validateToken(token)) {
|
||||
String username = jwtUtils.extractUsername(token);
|
||||
UserEntity userEntity = userRepository.findByUsername(username).orElseThrow(() -> new UsernameNotFoundException("User not found"));
|
||||
List<GrantedAuthority> authorities = getAuthorities(userEntity.getPermissions());
|
||||
BookLoreUserEntity bookLoreUserEntity = userRepository.findByUsername(username).orElseThrow(() -> new UsernameNotFoundException("User not found"));
|
||||
List<GrantedAuthority> authorities = getAuthorities(bookLoreUserEntity.getPermissions());
|
||||
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(username, null, authorities);
|
||||
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
|
||||
SecurityContextHolder.getContext().setAuthentication(authentication);
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
package com.adityachandel.booklore.config.security;
|
||||
|
||||
import io.jsonwebtoken.*;
|
||||
import com.adityachandel.booklore.model.entity.UserEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookLoreUserEntity;
|
||||
import io.jsonwebtoken.security.Keys;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@@ -13,7 +13,7 @@ import java.util.Date;
|
||||
public class JwtUtils {
|
||||
private final String secretKey = "G6u4m3g7M/b93k7m9a1h1Kw4l3D+5WqXldpl4nTjl4s=";
|
||||
|
||||
public String generateToken(UserEntity user) {
|
||||
public String generateToken(BookLoreUserEntity user) {
|
||||
SecretKey key = Keys.hmacShaKeyFor(secretKey.getBytes(StandardCharsets.UTF_8));
|
||||
Date now = new Date();
|
||||
Date expirationDate = new Date(now.getTime() + 1000 * 60 * 60 * 10);
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.adityachandel.booklore.controller;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.BookLoreUser;
|
||||
import com.adityachandel.booklore.model.dto.UserCreateRequest;
|
||||
import com.adityachandel.booklore.model.dto.request.UserLoginRequest;
|
||||
import com.adityachandel.booklore.model.dto.request.UserUpdateRequest;
|
||||
import com.adityachandel.booklore.service.UserService;
|
||||
import jakarta.validation.Valid;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@AllArgsConstructor
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/users")
|
||||
public class UserController {
|
||||
|
||||
private final UserService userService;
|
||||
|
||||
@GetMapping
|
||||
public ResponseEntity<List<BookLoreUser>> getAllUsers() {
|
||||
return ResponseEntity.ok(userService.getBookLoreUsers());
|
||||
}
|
||||
|
||||
@PutMapping("/{id}")
|
||||
public ResponseEntity<BookLoreUser> updateUser(@PathVariable Long id, @Valid @RequestBody UserUpdateRequest updateRequest) {
|
||||
BookLoreUser updatedUser = userService.updateUser(id, updateRequest);
|
||||
return ResponseEntity.ok(updatedUser);
|
||||
}
|
||||
|
||||
@DeleteMapping("/{id}")
|
||||
@PreAuthorize("hasRole('ADMIN')")
|
||||
public void deleteUser(@PathVariable Long id) {
|
||||
userService.deleteUser(id);
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import org.springframework.http.HttpStatus;
|
||||
@Getter
|
||||
public enum ApiError {
|
||||
BOOK_NOT_FOUND(HttpStatus.NOT_FOUND, "Book not found with ID: %d"),
|
||||
USER_NOT_FOUNDD(HttpStatus.NOT_FOUND, "User with ID %s not found"),
|
||||
UNSUPPORTED_BOOK_TYPE(HttpStatus.BAD_REQUEST, "Unsupported book type for viewer settings"),
|
||||
INVALID_VIEWER_SETTING(HttpStatus.BAD_REQUEST, "Invalid viewer setting for the book"),
|
||||
FILE_READ_ERROR(HttpStatus.INTERNAL_SERVER_ERROR, "Error reading files from path"),
|
||||
@@ -28,6 +29,8 @@ public enum ApiError {
|
||||
METADATA_LOCKED(HttpStatus.FORBIDDEN, "Attempt to update locked metadata fields for book with ID: %d"),
|
||||
USERNAME_ALREADY_TAKEN(HttpStatus.BAD_REQUEST, "Username already taken: %s"),
|
||||
USER_NOT_FOUND(HttpStatus.BAD_REQUEST, "User not found: %s"),
|
||||
CANNOT_DELETE_ADMIN(HttpStatus.FORBIDDEN, "Admin user cannot be deleted"),
|
||||
UNAUTHORIZED(HttpStatus.FORBIDDEN, "You do not have permission to perform this action"),
|
||||
INVALID_CREDENTIALS(HttpStatus.BAD_REQUEST, "Invalid credentials");
|
||||
|
||||
private final HttpStatus status;
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.adityachandel.booklore.mapper;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.BookLoreUser;
|
||||
import com.adityachandel.booklore.model.entity.BookLoreUserEntity;
|
||||
import com.adityachandel.booklore.model.entity.UserPermissionsEntity;
|
||||
import org.mapstruct.Mapper;
|
||||
import org.mapstruct.Mapping;
|
||||
|
||||
@Mapper(componentModel = "spring")
|
||||
public interface BookLoreUserMapper {
|
||||
|
||||
@Mapping(source = "permissions", target = "permissions")
|
||||
BookLoreUser toDto(BookLoreUserEntity entity);
|
||||
|
||||
default BookLoreUser.UserPermissions mapPermissions(UserPermissionsEntity permissions) {
|
||||
if (permissions == null) {
|
||||
return null;
|
||||
}
|
||||
BookLoreUser.UserPermissions dto = new BookLoreUser.UserPermissions();
|
||||
dto.setCanUpload(permissions.isPermissionUpload());
|
||||
dto.setCanDownload(permissions.isPermissionDownload());
|
||||
dto.setCanEditMetadata(permissions.isPermissionEditMetadata());
|
||||
return dto;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.adityachandel.booklore.model.dto;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class BookLoreUser {
|
||||
private Long id;
|
||||
private String username;
|
||||
private String name;
|
||||
private String email;
|
||||
private UserPermissions permissions;
|
||||
|
||||
@Data
|
||||
public static class UserPermissions {
|
||||
private boolean canUpload;
|
||||
private boolean canDownload;
|
||||
private boolean canEditMetadata;
|
||||
}
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package com.adityachandel.booklore.model.dto.request;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class UserUpdateRequest {
|
||||
private String name;
|
||||
private String email;
|
||||
private Permissions permissions;
|
||||
|
||||
@Data
|
||||
public static class Permissions {
|
||||
private boolean canUpload;
|
||||
private boolean canDownload;
|
||||
private boolean canEditMetadata;
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -12,7 +12,7 @@ import java.time.LocalDateTime;
|
||||
@NoArgsConstructor
|
||||
@Entity
|
||||
@Table(name = "users")
|
||||
public class UserEntity {
|
||||
public class BookLoreUserEntity {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
+1
-1
@@ -18,7 +18,7 @@ public class UserPermissionsEntity {
|
||||
|
||||
@OneToOne
|
||||
@JoinColumn(name = "user_id", nullable = false, unique = true)
|
||||
private UserEntity user;
|
||||
private BookLoreUserEntity user;
|
||||
|
||||
@Column(name = "permission_upload", nullable = false)
|
||||
private boolean permissionUpload = false;
|
||||
|
||||
+4
-4
@@ -1,15 +1,15 @@
|
||||
package com.adityachandel.booklore.repository;
|
||||
|
||||
import com.adityachandel.booklore.model.entity.UserEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookLoreUserEntity;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
@Repository
|
||||
public interface UserRepository extends JpaRepository<UserEntity, Long> {
|
||||
public interface UserRepository extends JpaRepository<BookLoreUserEntity, Long> {
|
||||
|
||||
Optional<UserEntity> findByUsername(String username);
|
||||
Optional<BookLoreUserEntity> findByUsername(String username);
|
||||
|
||||
Optional<UserEntity> findByEmail(String email);
|
||||
Optional<BookLoreUserEntity> findByEmail(String email);
|
||||
}
|
||||
|
||||
@@ -2,52 +2,60 @@ package com.adityachandel.booklore.service;
|
||||
|
||||
import com.adityachandel.booklore.config.security.JwtUtils;
|
||||
import com.adityachandel.booklore.exception.ApiError;
|
||||
import com.adityachandel.booklore.mapper.BookLoreUserMapper;
|
||||
import com.adityachandel.booklore.model.dto.BookLoreUser;
|
||||
import com.adityachandel.booklore.model.dto.UserCreateRequest;
|
||||
import com.adityachandel.booklore.model.dto.request.UserLoginRequest;
|
||||
import com.adityachandel.booklore.model.entity.UserEntity;
|
||||
import com.adityachandel.booklore.model.dto.request.UserUpdateRequest;
|
||||
import com.adityachandel.booklore.model.entity.BookLoreUserEntity;
|
||||
import com.adityachandel.booklore.model.entity.UserPermissionsEntity;
|
||||
import com.adityachandel.booklore.repository.UserRepository;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class UserService {
|
||||
|
||||
private final UserRepository userRepository;
|
||||
private final BookLoreUserMapper bookLoreUserMapper;
|
||||
private final PasswordEncoder passwordEncoder;
|
||||
private final JwtUtils jwtUtils;
|
||||
|
||||
public ResponseEntity<Map<String, String>> registerUser(UserCreateRequest request) {
|
||||
Optional<UserEntity> existingUser = userRepository.findByUsername(request.getUsername());
|
||||
Optional<BookLoreUserEntity> existingUser = userRepository.findByUsername(request.getUsername());
|
||||
if (existingUser.isPresent()) {
|
||||
throw ApiError.USERNAME_ALREADY_TAKEN.createException(request.getUsername());
|
||||
}
|
||||
|
||||
UserEntity userEntity = new UserEntity();
|
||||
userEntity.setUsername(request.getUsername());
|
||||
userEntity.setPasswordHash(passwordEncoder.encode(request.getPassword()));
|
||||
userEntity.setName(request.getName());
|
||||
userEntity.setEmail(request.getEmail());
|
||||
BookLoreUserEntity bookLoreUserEntity = new BookLoreUserEntity();
|
||||
bookLoreUserEntity.setUsername(request.getUsername());
|
||||
bookLoreUserEntity.setPasswordHash(passwordEncoder.encode(request.getPassword()));
|
||||
bookLoreUserEntity.setName(request.getName());
|
||||
bookLoreUserEntity.setEmail(request.getEmail());
|
||||
|
||||
UserPermissionsEntity permissions = new UserPermissionsEntity();
|
||||
permissions.setUser(userEntity);
|
||||
permissions.setUser(bookLoreUserEntity);
|
||||
permissions.setPermissionUpload(request.isPermissionUpload());
|
||||
permissions.setPermissionDownload(request.isPermissionDownload());
|
||||
permissions.setPermissionEditMetadata(request.isPermissionEditMetadata());
|
||||
|
||||
userEntity.setPermissions(permissions);
|
||||
bookLoreUserEntity.setPermissions(permissions);
|
||||
|
||||
userRepository.save(userEntity);
|
||||
userRepository.save(bookLoreUserEntity);
|
||||
|
||||
String token = jwtUtils.generateToken(userEntity);
|
||||
String token = jwtUtils.generateToken(bookLoreUserEntity);
|
||||
|
||||
Map<String, String> response = new HashMap<>();
|
||||
response.put("token", token);
|
||||
@@ -56,7 +64,7 @@ public class UserService {
|
||||
}
|
||||
|
||||
public ResponseEntity<Map<String, String>> loginUser(UserLoginRequest loginRequest) {
|
||||
UserEntity user = userRepository.findByUsername(loginRequest.getUsername())
|
||||
BookLoreUserEntity user = userRepository.findByUsername(loginRequest.getUsername())
|
||||
.orElseThrow(() -> ApiError.USER_NOT_FOUND.createException(loginRequest.getUsername()));
|
||||
|
||||
if (!passwordEncoder.matches(loginRequest.getPassword(), user.getPasswordHash())) {
|
||||
@@ -66,4 +74,41 @@ public class UserService {
|
||||
String token = jwtUtils.generateToken(user);
|
||||
return ResponseEntity.ok(Map.of("token", token));
|
||||
}
|
||||
|
||||
public List<BookLoreUser> getBookLoreUsers() {
|
||||
return userRepository.findAll()
|
||||
.stream()
|
||||
.map(bookLoreUserMapper::toDto)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
public BookLoreUser updateUser(Long id, UserUpdateRequest updateRequest) {
|
||||
BookLoreUserEntity user = userRepository.findById(id).orElseThrow(() -> ApiError.USER_NOT_FOUND.createException(id));
|
||||
user.setName(updateRequest.getName());
|
||||
user.setEmail(updateRequest.getEmail());
|
||||
user.getPermissions().setPermissionUpload(updateRequest.getPermissions().isCanUpload());
|
||||
user.getPermissions().setPermissionDownload(updateRequest.getPermissions().isCanDownload());
|
||||
user.getPermissions().setPermissionEditMetadata(updateRequest.getPermissions().isCanEditMetadata());
|
||||
userRepository.save(user);
|
||||
return bookLoreUserMapper.toDto(user);
|
||||
}
|
||||
|
||||
public void deleteUser(Long id) {
|
||||
BookLoreUserEntity user = userRepository.findById(id).orElseThrow(() -> ApiError.USER_NOT_FOUND.createException(id));
|
||||
|
||||
if (user.getPermissions().isPermissionAdmin()) {
|
||||
throw ApiError.CANNOT_DELETE_ADMIN.createException();
|
||||
}
|
||||
|
||||
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
|
||||
if (principal instanceof UserDetails userDetails) {
|
||||
if (userDetails.getAuthorities().stream().noneMatch(auth -> auth.getAuthority().equals("ROLE_ADMIN"))) {
|
||||
throw ApiError.UNAUTHORIZED.createException();
|
||||
}
|
||||
}
|
||||
|
||||
userRepository.delete(user);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -134,4 +134,8 @@ export class LibraryService {
|
||||
map(state => (state.books || []).filter(book => book.libraryId === libraryId).length)
|
||||
);
|
||||
}
|
||||
|
||||
getLibrariesFromState(): Library[] {
|
||||
return this.libraryStateSubject.value.libraries || [];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1 +1,62 @@
|
||||
<p>admin works!</p>
|
||||
<div class="p-4">
|
||||
<p-button outlined="true" label="Create User" (onClick)="openCreateUserDialog()"></p-button>
|
||||
|
||||
<p-table [value]="users" class="mt-4">
|
||||
<ng-template pTemplate="header">
|
||||
<tr>
|
||||
<th>Username</th>
|
||||
<th>Full Name</th>
|
||||
<th>Email</th>
|
||||
<th style="width: 100px;">Can Upload</th>
|
||||
<th style="width: 100px;">Can Download</th>
|
||||
<th style="width: 100px;">Can Edit Metadata</th>
|
||||
<th style="width: 100px;">Edit</th>
|
||||
<th style="width: 100px;">Delete</th>
|
||||
</tr>
|
||||
</ng-template>
|
||||
|
||||
<ng-template pTemplate="body" let-user>
|
||||
<tr>
|
||||
<td>{{ user.username }}</td>
|
||||
<td>
|
||||
<input *ngIf="user.isEditing" type="text" [(ngModel)]="user.name" class="p-inputtext w-full"/>
|
||||
<span *ngIf="!user.isEditing">{{ user.name }}</span>
|
||||
</td>
|
||||
<td>
|
||||
<input *ngIf="user.isEditing" type="email" [(ngModel)]="user.email" class="p-inputtext w-full"/>
|
||||
<span *ngIf="!user.isEditing">{{ user.email }}</span>
|
||||
</td>
|
||||
<td class="text-center">
|
||||
<p-checkbox [binary]="true" [(ngModel)]="user.permissions.canUpload" *ngIf="user.isEditing"></p-checkbox>
|
||||
<p-checkbox [binary]="true" [(ngModel)]="user.permissions.canUpload" disabled *ngIf="!user.isEditing"></p-checkbox>
|
||||
</td>
|
||||
<td class="text-center">
|
||||
<p-checkbox [binary]="true" [(ngModel)]="user.permissions.canDownload" *ngIf="user.isEditing"></p-checkbox>
|
||||
<p-checkbox [binary]="true" [(ngModel)]="user.permissions.canDownload" disabled *ngIf="!user.isEditing"></p-checkbox>
|
||||
</td>
|
||||
<td class="text-center">
|
||||
<p-checkbox [binary]="true" [(ngModel)]="user.permissions.canEditMetadata" *ngIf="user.isEditing"></p-checkbox>
|
||||
<p-checkbox [binary]="true" [(ngModel)]="user.permissions.canEditMetadata" disabled *ngIf="!user.isEditing"></p-checkbox>
|
||||
</td>
|
||||
<td class="text-center">
|
||||
<ng-container *ngIf="user.username !== 'admin'">
|
||||
<p-button *ngIf="!user.isEditing" icon="pi pi-pencil" outlined="true" severity="primary" (onClick)="toggleEdit(user)"></p-button>
|
||||
<p-button *ngIf="user.isEditing" icon="pi pi-check" outlined="true" severity="success" (onClick)="saveUser(user)"></p-button>
|
||||
<p-button *ngIf="user.isEditing" icon="pi pi-times" outlined="true" severity="danger" (onClick)="toggleEdit(user)"></p-button>
|
||||
</ng-container>
|
||||
<p-button *ngIf="user.username === 'admin'"
|
||||
icon="pi pi-pencil"
|
||||
outlined="true"
|
||||
severity="primary"
|
||||
[ngStyle]="{'visibility': 'hidden'}">
|
||||
</p-button>
|
||||
</td>
|
||||
<td class="text-center">
|
||||
<ng-container *ngIf="user.username !== 'admin'">
|
||||
<p-button icon="pi pi-trash" outlined="true" severity="danger" (onClick)="deleteUser(user)"></p-button>
|
||||
</ng-container>
|
||||
</td>
|
||||
</tr>
|
||||
</ng-template>
|
||||
</p-table>
|
||||
</div>
|
||||
|
||||
@@ -1,11 +1,98 @@
|
||||
import { Component } from '@angular/core';
|
||||
import {Component, inject, OnInit} from '@angular/core';
|
||||
import {FormsModule} from '@angular/forms';
|
||||
import {Button} from 'primeng/button';
|
||||
import {DialogService, DynamicDialogRef} from 'primeng/dynamicdialog';
|
||||
import {CreateUserDialogComponent} from './create-user-dialog/create-user-dialog.component';
|
||||
import {TableModule} from 'primeng/table';
|
||||
import {NgIf, NgStyle} from '@angular/common';
|
||||
import {User, UserService} from '../../../../user.service';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {Checkbox} from 'primeng/checkbox';
|
||||
|
||||
@Component({
|
||||
selector: 'app-admin',
|
||||
imports: [],
|
||||
imports: [FormsModule, Button, TableModule, NgIf, Checkbox, NgStyle],
|
||||
templateUrl: './admin.component.html',
|
||||
styleUrl: './admin.component.scss'
|
||||
styleUrl: './admin.component.scss',
|
||||
})
|
||||
export class AdminComponent {
|
||||
export class AdminComponent implements OnInit {
|
||||
ref: DynamicDialogRef | undefined;
|
||||
private dialogService = inject(DialogService);
|
||||
private userService = inject(UserService);
|
||||
private messageService = inject(MessageService);
|
||||
|
||||
users: any[] = [];
|
||||
|
||||
ngOnInit() {
|
||||
this.loadUsers();
|
||||
}
|
||||
|
||||
loadUsers() {
|
||||
this.userService.getUsers().subscribe({
|
||||
next: (data) => {
|
||||
this.users = data.map(user => ({
|
||||
...user,
|
||||
isEditing: false,
|
||||
}));
|
||||
},
|
||||
error: () => {
|
||||
this.messageService.add({severity: 'error', summary: 'Error', detail: 'Failed to fetch users'});
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
openCreateUserDialog() {
|
||||
this.ref = this.dialogService.open(CreateUserDialogComponent, {
|
||||
header: 'Create New User',
|
||||
modal: true,
|
||||
closable: true,
|
||||
style: {position: 'absolute', top: '15%'},
|
||||
});
|
||||
this.ref.onClose.subscribe((result) => {
|
||||
if (result) {
|
||||
this.loadUsers();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
toggleEdit(user: any) {
|
||||
user.isEditing = !user.isEditing;
|
||||
if (!user.isEditing) {
|
||||
this.loadUsers();
|
||||
}
|
||||
}
|
||||
|
||||
saveUser(user: any) {
|
||||
this.userService.updateUser(user.id, {
|
||||
name: user.name,
|
||||
email: user.email,
|
||||
permissions: user.permissions,
|
||||
}).subscribe({
|
||||
next: () => {
|
||||
user.isEditing = false;
|
||||
this.messageService.add({severity: 'success', summary: 'Success', detail: 'User updated successfully'});
|
||||
},
|
||||
error: () => {
|
||||
this.messageService.add({severity: 'error', summary: 'Error', detail: 'Failed to update user'});
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
deleteUser(user: User) {
|
||||
if (confirm(`Are you sure you want to delete ${user.username}?`)) {
|
||||
this.userService.deleteUser(user.id).subscribe({
|
||||
next: () => {
|
||||
this.messageService.add({severity: 'success', summary: 'Success', detail: `User ${user.username} deleted successfully`});
|
||||
this.loadUsers();
|
||||
},
|
||||
error: (err) => {
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: 'Error',
|
||||
detail: err.error?.message || `Failed to delete user ${user.username}`,
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
<div class="space-y-6 p-6">
|
||||
<div class="flex items-center gap-4">
|
||||
<label class="w-40 text-right font-medium">Full Name:</label>
|
||||
<input type="text" pInputText [(ngModel)]="name" placeholder="Enter full name..." class="w-full md:w-80"/>
|
||||
</div>
|
||||
|
||||
<div class="flex items-center gap-4">
|
||||
<label class="w-40 text-right font-medium">Email:</label>
|
||||
<input type="email" pInputText [(ngModel)]="email" placeholder="Enter email..." class="w-full md:w-80"/>
|
||||
</div>
|
||||
|
||||
<div class="flex items-center gap-4">
|
||||
<label class="w-40 text-right font-medium">Username:</label>
|
||||
<input type="text" pInputText [(ngModel)]="username" placeholder="Enter username..." class="w-full md:w-80"/>
|
||||
</div>
|
||||
|
||||
<div class="flex items-center gap-4">
|
||||
<label class="w-40 text-right font-medium">Password:</label>
|
||||
<input type="password" pInputText [(ngModel)]="password" placeholder="Enter password..." class="w-full md:w-80"/>
|
||||
</div>
|
||||
|
||||
<div class="flex items-center gap-4">
|
||||
<label class="w-40 text-right font-medium">Accessible Libraries:</label>
|
||||
<p-multiselect
|
||||
[options]="libraries"
|
||||
[(ngModel)]="selectedLibraries"
|
||||
placeholder="Select Libraries"
|
||||
optionLabel="name"
|
||||
display="chip"
|
||||
class="w-full md:w-80"
|
||||
appendTo="body">
|
||||
</p-multiselect>
|
||||
</div>
|
||||
|
||||
<!-- Grouped Permissions -->
|
||||
<div>
|
||||
<p class="text-right w-40 font-medium">Permissions:</p>
|
||||
<div class="flex flex-col gap-2 pl-44">
|
||||
<div class="flex items-center gap-2">
|
||||
<p-checkbox [(ngModel)]="canUpload" [binary]="true"></p-checkbox>
|
||||
<label>Upload Books</label>
|
||||
</div>
|
||||
|
||||
<div class="flex items-center gap-2">
|
||||
<p-checkbox [(ngModel)]="canDownload" [binary]="true"></p-checkbox>
|
||||
<label>Download Books</label>
|
||||
</div>
|
||||
|
||||
<div class="flex items-center gap-2">
|
||||
<p-checkbox [(ngModel)]="canEditMetadata" [binary]="true"></p-checkbox>
|
||||
<label>Edit Metadata</label>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex justify-end">
|
||||
<p-button
|
||||
label="Create User"
|
||||
[disabled]="!username || password.length < 6 || !name || !email"
|
||||
(onClick)="createUser()">
|
||||
</p-button>
|
||||
</div>
|
||||
</div>
|
||||
+86
@@ -0,0 +1,86 @@
|
||||
import {Component, inject, OnInit} from '@angular/core';
|
||||
import {InputText} from 'primeng/inputtext';
|
||||
import {FormsModule, ReactiveFormsModule} from '@angular/forms';
|
||||
import {Checkbox} from 'primeng/checkbox';
|
||||
import {MultiSelectModule} from 'primeng/multiselect';
|
||||
import {Library} from '../../../../../book/model/library.model';
|
||||
import {Button} from 'primeng/button';
|
||||
import {LibraryService} from '../../../../../book/service/library.service';
|
||||
import {UserService} from '../../../../../user.service';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {DynamicDialogRef} from 'primeng/dynamicdialog';
|
||||
|
||||
@Component({
|
||||
selector: 'app-create-user-dialog',
|
||||
standalone: true,
|
||||
imports: [
|
||||
InputText,
|
||||
ReactiveFormsModule,
|
||||
FormsModule,
|
||||
Checkbox,
|
||||
MultiSelectModule,
|
||||
Button
|
||||
],
|
||||
templateUrl: './create-user-dialog.component.html',
|
||||
styleUrl: './create-user-dialog.component.scss'
|
||||
})
|
||||
export class CreateUserDialogComponent implements OnInit {
|
||||
libraries: Library[] = [];
|
||||
selectedLibraries: Library[] = [];
|
||||
|
||||
username: string = '';
|
||||
password: string = '';
|
||||
name: string = '';
|
||||
email: string = '';
|
||||
canUpload: boolean = false;
|
||||
canDownload: boolean = false;
|
||||
canEditMetadata: boolean = false;
|
||||
|
||||
private libraryService = inject(LibraryService);
|
||||
private userService = inject(UserService);
|
||||
private messageService = inject(MessageService);
|
||||
private ref = inject(DynamicDialogRef);
|
||||
|
||||
ngOnInit() {
|
||||
this.libraries = this.libraryService.getLibrariesFromState();
|
||||
}
|
||||
|
||||
createUser() {
|
||||
if (!this.username || this.password.length < 6 || !this.name || !this.email || this.selectedLibraries.length === 0) {
|
||||
this.messageService.add({
|
||||
severity: 'warn',
|
||||
summary: 'Validation Error',
|
||||
detail: 'Please fill all required fields correctly.'
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const userData = {
|
||||
username: this.username,
|
||||
password: this.password,
|
||||
name: this.name,
|
||||
email: this.email,
|
||||
permissionUpload: this.canUpload,
|
||||
permissionDownload: this.canDownload,
|
||||
permissionEditMetadata: this.canEditMetadata
|
||||
};
|
||||
|
||||
this.userService.createUser(userData).subscribe({
|
||||
next: response => {
|
||||
this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: 'User Created',
|
||||
detail: response.message
|
||||
});
|
||||
this.ref.close(true);
|
||||
},
|
||||
error: err => {
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: 'Error',
|
||||
detail: 'Failed to create user: ' + err.error.message
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -10,7 +10,6 @@ import {DashboardScrollerComponent} from '../dashboard-scroller/dashboard-scroll
|
||||
import {BookService} from '../../../book/service/book.service';
|
||||
import {BookState} from '../../../book/model/state/book-state.model';
|
||||
import {Book} from '../../../book/model/book.model';
|
||||
import {LibraryState} from '../../../book/model/state/library-state.model';
|
||||
import {Divider} from 'primeng/divider';
|
||||
|
||||
@Component({
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
import {inject, Injectable} from '@angular/core';
|
||||
import {HttpClient} from '@angular/common/http';
|
||||
import {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;
|
||||
};
|
||||
}
|
||||
|
||||
export interface User {
|
||||
id: number;
|
||||
username: string;
|
||||
name: string;
|
||||
email: string;
|
||||
permissions: {
|
||||
canUpload: boolean;
|
||||
canDownload: boolean;
|
||||
canEditMetadata: boolean;
|
||||
};
|
||||
isEditing?: boolean;
|
||||
}
|
||||
|
||||
@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 }> {
|
||||
return this.http.post<{ message: string }>(this.apiUrl, userData);
|
||||
}
|
||||
|
||||
getUsers(): Observable<User[]> {
|
||||
return this.http.get<User[]>(this.userUrl);
|
||||
}
|
||||
|
||||
updateUser(userId: number, updateData: UserUpdateRequest): Observable<{ message: string }> {
|
||||
return this.http.put<{ message: string }>(`${this.userUrl}/${userId}`, updateData);
|
||||
}
|
||||
|
||||
deleteUser(userId: number): Observable<void> {
|
||||
return this.http.delete<void>(`${this.userUrl}/${userId}`);
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user