- Implement change password on first login
- Implement admin can reset other users' password
This commit is contained in:
+7
-1
@@ -37,7 +37,13 @@ public class AuthenticationService {
|
||||
String accessToken = jwtUtils.generateAccessToken(user);
|
||||
String refreshToken = jwtUtils.generateRefreshToken(user);
|
||||
|
||||
return ResponseEntity.ok(Map.of("accessToken", accessToken, "refreshToken", refreshToken));
|
||||
boolean isDefaultPassword = user.isDefaultPassword();
|
||||
|
||||
return ResponseEntity.ok(Map.of(
|
||||
"accessToken", accessToken,
|
||||
"refreshToken", refreshToken,
|
||||
"isDefaultPassword", String.valueOf(isDefaultPassword)
|
||||
));
|
||||
}
|
||||
|
||||
public ResponseEntity<Map<String, String>> refreshToken(String refreshToken) {
|
||||
|
||||
+1
@@ -90,6 +90,7 @@ public class JwtAuthenticationFilter extends OncePerRequestFilter {
|
||||
bookLoreUser.setUsername(userEntity.getUsername());
|
||||
bookLoreUser.setName(userEntity.getName());
|
||||
bookLoreUser.setEmail(userEntity.getEmail());
|
||||
bookLoreUser.setDefaultPassword(userEntity.isDefaultPassword());
|
||||
bookLoreUser.setPermissions(permissions);
|
||||
|
||||
bookLoreUser.setBookPreferences(userEntity.getBookPreferences());
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
package com.adityachandel.booklore.controller;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.request.ChangePasswordRequest;
|
||||
import com.adityachandel.booklore.model.dto.request.ChangeUserPasswordRequest;
|
||||
import com.adityachandel.booklore.model.dto.settings.BookPreferences;
|
||||
import com.adityachandel.booklore.model.dto.BookLoreUser;
|
||||
import com.adityachandel.booklore.model.dto.request.UserUpdateRequest;
|
||||
@@ -49,6 +51,19 @@ public class UserController {
|
||||
userService.deleteUser(id);
|
||||
}
|
||||
|
||||
@PutMapping("/change-password")
|
||||
public ResponseEntity<?> changePassword(@RequestBody ChangePasswordRequest request) {
|
||||
userService.changePassword(request);
|
||||
return ResponseEntity.ok().build();
|
||||
}
|
||||
|
||||
@PutMapping("/change-user-password")
|
||||
@PreAuthorize("@securityUtil.isAdmin()")
|
||||
public ResponseEntity<?> changeUserPassword(@RequestBody ChangeUserPasswordRequest request) {
|
||||
userService.changeUserPassword(request);
|
||||
return ResponseEntity.ok().build();
|
||||
}
|
||||
|
||||
@PutMapping("/{id}/book-preferences")
|
||||
@PreAuthorize("@securityUtil.isSelf(#id)")
|
||||
public void updateUserBookPreferences(@PathVariable Long id, @RequestBody BookPreferences bookPreferences) {
|
||||
|
||||
@@ -31,6 +31,8 @@ public enum ApiError {
|
||||
USER_NOT_FOUND(HttpStatus.BAD_REQUEST, "User not found: %s"),
|
||||
CANNOT_DELETE_ADMIN(HttpStatus.FORBIDDEN, "Admin user cannot be deleted"),
|
||||
UNAUTHORIZED(HttpStatus.FORBIDDEN, "%s"),
|
||||
PASSWORD_INCORRECT(HttpStatus.BAD_REQUEST, "Incorrect current password"),
|
||||
PASSWORD_WEAK(HttpStatus.BAD_REQUEST, "New password is not strong enough. It must be at least 8 characters long, contain an uppercase letter, a lowercase letter, a number, and a special character."),
|
||||
INVALID_CREDENTIALS(HttpStatus.BAD_REQUEST, "Invalid credentials");
|
||||
|
||||
private final HttpStatus status;
|
||||
|
||||
+7
@@ -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.http.converter.HttpMessageNotReadableException;
|
||||
import org.springframework.security.access.AccessDeniedException;
|
||||
import org.springframework.web.bind.MethodArgumentNotValidException;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
@@ -24,6 +25,12 @@ public class GlobalExceptionHandler {
|
||||
return new ResponseEntity<>(errorResponse, ex.getStatus());
|
||||
}
|
||||
|
||||
@ExceptionHandler(HttpMessageNotReadableException.class)
|
||||
public ResponseEntity<ErrorResponse> handleHttpMessageNotReadableException(HttpMessageNotReadableException ex) {
|
||||
ErrorResponse errorResponse = new ErrorResponse(HttpStatus.BAD_REQUEST.value(), "Request body is missing or malformed: " + ex.getMostSpecificCause().getMessage());
|
||||
return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
|
||||
@ExceptionHandler(MethodArgumentNotValidException.class)
|
||||
public ResponseEntity<ErrorResponse> handleValidationExceptions(MethodArgumentNotValidException ex) {
|
||||
List<String> errors = ex.getBindingResult()
|
||||
|
||||
@@ -9,6 +9,7 @@ import java.util.List;
|
||||
public class BookLoreUser {
|
||||
private Long id;
|
||||
private String username;
|
||||
private boolean isDefaultPassword;
|
||||
private String name;
|
||||
private String email;
|
||||
private List<Library> assignedLibraries;
|
||||
|
||||
@@ -14,7 +14,6 @@ public class UserCreateRequest {
|
||||
private boolean permissionUpload;
|
||||
private boolean permissionDownload;
|
||||
private boolean permissionEditMetadata;
|
||||
private boolean permissionManipulateLibrary;
|
||||
|
||||
private Set<Long> selectedLibraries;
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package com.adityachandel.booklore.model.dto.request;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class ChangePasswordRequest {
|
||||
private String currentPassword;
|
||||
private String newPassword;
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package com.adityachandel.booklore.model.dto.request;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class ChangeUserPasswordRequest {
|
||||
private Long userId;
|
||||
private String newPassword;
|
||||
}
|
||||
+4
-11
@@ -29,6 +29,9 @@ public class BookLoreUserEntity {
|
||||
@Column(name = "password_hash", nullable = false)
|
||||
private String passwordHash;
|
||||
|
||||
@Column(name = "is_default_password", nullable = false)
|
||||
private boolean isDefaultPassword;
|
||||
|
||||
@Column(nullable = false)
|
||||
private String name;
|
||||
|
||||
@@ -38,9 +41,6 @@ public class BookLoreUserEntity {
|
||||
@Column(name = "created_at", nullable = false, updatable = false)
|
||||
private LocalDateTime createdAt;
|
||||
|
||||
@Column(name = "updated_at")
|
||||
private LocalDateTime updatedAt;
|
||||
|
||||
@Column(name = "book_preferences")
|
||||
@Convert(converter = BookPreferencesConverter.class)
|
||||
private BookPreferences bookPreferences;
|
||||
@@ -61,13 +61,6 @@ public class BookLoreUserEntity {
|
||||
|
||||
@PrePersist
|
||||
public void prePersist() {
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
this.createdAt = now;
|
||||
this.updatedAt = now;
|
||||
}
|
||||
|
||||
@PreUpdate
|
||||
public void preUpdate() {
|
||||
this.updatedAt = LocalDateTime.now();
|
||||
this.createdAt = LocalDateTime.now();
|
||||
}
|
||||
}
|
||||
+2
-1
@@ -39,6 +39,7 @@ public class UserCreatorService {
|
||||
|
||||
BookLoreUserEntity user = new BookLoreUserEntity();
|
||||
user.setUsername(request.getUsername());
|
||||
user.setDefaultPassword(true);
|
||||
user.setPasswordHash(passwordEncoder.encode(request.getPassword()));
|
||||
user.setName(request.getName());
|
||||
user.setEmail(request.getEmail());
|
||||
@@ -48,7 +49,6 @@ public class UserCreatorService {
|
||||
permissions.setPermissionUpload(request.isPermissionUpload());
|
||||
permissions.setPermissionDownload(request.isPermissionDownload());
|
||||
permissions.setPermissionEditMetadata(request.isPermissionEditMetadata());
|
||||
permissions.setPermissionManipulateLibrary(request.isPermissionManipulateLibrary());
|
||||
user.setPermissions(permissions);
|
||||
|
||||
user.setBookPreferences(buildDefaultBookPreferences());
|
||||
@@ -71,6 +71,7 @@ public class UserCreatorService {
|
||||
BookLoreUserEntity user = new BookLoreUserEntity();
|
||||
user.setUsername("admin");
|
||||
user.setPasswordHash(passwordEncoder.encode("admin123"));
|
||||
user.setDefaultPassword(true);
|
||||
user.setName("Administrator");
|
||||
user.setEmail("admin@email.com");
|
||||
|
||||
|
||||
+33
-2
@@ -3,6 +3,8 @@ package com.adityachandel.booklore.service.user;
|
||||
import com.adityachandel.booklore.config.security.AuthenticationService;
|
||||
import com.adityachandel.booklore.exception.ApiError;
|
||||
import com.adityachandel.booklore.mapper.BookLoreUserMapper;
|
||||
import com.adityachandel.booklore.model.dto.request.ChangePasswordRequest;
|
||||
import com.adityachandel.booklore.model.dto.request.ChangeUserPasswordRequest;
|
||||
import com.adityachandel.booklore.model.dto.settings.BookPreferences;
|
||||
import com.adityachandel.booklore.model.dto.BookLoreUser;
|
||||
import com.adityachandel.booklore.model.dto.request.UserUpdateRequest;
|
||||
@@ -13,6 +15,7 @@ import com.adityachandel.booklore.repository.UserRepository;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
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.List;
|
||||
@@ -26,6 +29,7 @@ public class UserService {
|
||||
private final BookLoreUserMapper bookLoreUserMapper;
|
||||
private final LibraryRepository libraryRepository;
|
||||
private final AuthenticationService authenticationService;
|
||||
private final PasswordEncoder passwordEncoder;
|
||||
|
||||
public List<BookLoreUser> getBookLoreUsers() {
|
||||
return userRepository.findAll()
|
||||
@@ -83,7 +87,34 @@ public class UserService {
|
||||
}
|
||||
|
||||
public BookLoreUser getMyself() {
|
||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||
return user;
|
||||
return authenticationService.getAuthenticatedUser();
|
||||
}
|
||||
|
||||
public void changePassword(ChangePasswordRequest changePasswordRequest) {
|
||||
BookLoreUser bookLoreUser = authenticationService.getAuthenticatedUser();
|
||||
BookLoreUserEntity bookLoreUserEntity = userRepository.findById(bookLoreUser.getId()).orElseThrow(() -> ApiError.USER_NOT_FOUND.createException(bookLoreUser.getId()));
|
||||
if (!passwordEncoder.matches(changePasswordRequest.getCurrentPassword(), bookLoreUserEntity.getPasswordHash())) {
|
||||
throw ApiError.PASSWORD_INCORRECT.createException();
|
||||
}
|
||||
if (!isPasswordStrong(changePasswordRequest.getNewPassword())) {
|
||||
throw ApiError.PASSWORD_WEAK.createException();
|
||||
}
|
||||
bookLoreUserEntity.setDefaultPassword(false);
|
||||
bookLoreUserEntity.setPasswordHash(passwordEncoder.encode(changePasswordRequest.getNewPassword()));
|
||||
userRepository.save(bookLoreUserEntity);
|
||||
}
|
||||
|
||||
public void changeUserPassword(ChangeUserPasswordRequest request) {
|
||||
BookLoreUserEntity userEntity = userRepository.findById(request.getUserId()).orElseThrow(() -> ApiError.USER_NOT_FOUND.createException(request.getUserId()));
|
||||
if (!isPasswordStrong(request.getNewPassword())) {
|
||||
throw ApiError.PASSWORD_WEAK.createException();
|
||||
}
|
||||
userEntity.setPasswordHash(passwordEncoder.encode(request.getNewPassword()));
|
||||
userRepository.save(userEntity);
|
||||
}
|
||||
|
||||
private boolean isPasswordStrong(String password) {
|
||||
String passwordPattern = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[@$!%*?&])[A-Za-z\\d@$!%*?&]{8,}$";
|
||||
return password.matches(passwordPattern);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,16 @@
|
||||
CREATE TABLE IF NOT EXISTS users
|
||||
(
|
||||
id BIGINT AUTO_INCREMENT PRIMARY KEY,
|
||||
username VARCHAR(255) NOT NULL UNIQUE,
|
||||
password_hash VARCHAR(255) NOT NULL,
|
||||
is_default_password BOOLEAN NOT NULL DEFAULT TRUE,
|
||||
name VARCHAR(255) NOT NULL,
|
||||
email VARCHAR(255) UNIQUE,
|
||||
book_preferences TEXT NOT NULL,
|
||||
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
|
||||
CREATE TABLE IF NOT EXISTS library
|
||||
(
|
||||
id BIGINT AUTO_INCREMENT PRIMARY KEY,
|
||||
@@ -115,11 +128,11 @@ CREATE TABLE IF NOT EXISTS category
|
||||
|
||||
CREATE TABLE IF NOT EXISTS pdf_viewer_preference
|
||||
(
|
||||
id BIGINT AUTO_INCREMENT PRIMARY KEY,
|
||||
user_id BIGINT NOT NULL,
|
||||
book_id BIGINT NOT NULL,
|
||||
zoom VARCHAR(16) NULL,
|
||||
spread VARCHAR(16) NULL,
|
||||
id BIGINT AUTO_INCREMENT PRIMARY KEY,
|
||||
user_id BIGINT NOT NULL,
|
||||
book_id BIGINT NOT NULL,
|
||||
zoom VARCHAR(16) NULL,
|
||||
spread VARCHAR(16) NULL,
|
||||
UNIQUE (user_id, book_id)
|
||||
);
|
||||
|
||||
@@ -158,19 +171,6 @@ CREATE INDEX IF NOT EXISTS idx_book_metadata_id ON book_metadata_author_mapping
|
||||
CREATE INDEX IF NOT EXISTS idx_author_id ON book_metadata_author_mapping (author_id);
|
||||
|
||||
|
||||
CREATE TABLE IF NOT EXISTS users
|
||||
(
|
||||
id BIGINT AUTO_INCREMENT PRIMARY KEY,
|
||||
username VARCHAR(255) NOT NULL UNIQUE,
|
||||
password_hash VARCHAR(255) NOT NULL,
|
||||
name VARCHAR(255) NOT NULL,
|
||||
email VARCHAR(255) UNIQUE,
|
||||
book_preferences TEXT NOT NULL,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
|
||||
CREATE TABLE IF NOT EXISTS user_permissions
|
||||
(
|
||||
id BIGINT AUTO_INCREMENT PRIMARY KEY,
|
||||
|
||||
@@ -7,6 +7,7 @@ import {AuthGuard} from './auth.guard';
|
||||
import {SettingsComponent} from './core/component/settings/settings.component';
|
||||
import {PdfViewerComponent} from './book/components/pdf-viewer/pdf-viewer.component';
|
||||
import {EpubViewerComponent} from './book/components/epub-viewer/component/epub-viewer.component';
|
||||
import {ChangePasswordComponent} from './core/component/change-password/change-password.component';
|
||||
|
||||
export const routes: Routes = [
|
||||
{
|
||||
@@ -36,5 +37,6 @@ export const routes: Routes = [
|
||||
canActivate: [AuthGuard]
|
||||
},
|
||||
{path: 'login', component: LoginComponent},
|
||||
{path: 'change-password', component: ChangePasswordComponent},
|
||||
{path: '**', redirectTo: 'login', pathMatch: 'full'}
|
||||
];
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
<div class="change-password-container">
|
||||
<div class="change-password-wrapper">
|
||||
<p-card class="change-password-card p-fluid">
|
||||
|
||||
<ng-template pTemplate="content">
|
||||
<form #changePasswordForm="ngForm">
|
||||
<div class="p-field">
|
||||
<label for="currentPassword">Current Password</label>
|
||||
<p-password id="currentPassword" [(ngModel)]="currentPassword" name="currentPassword" [feedback]="false" required fluid></p-password>
|
||||
</div>
|
||||
|
||||
<div class="p-field">
|
||||
<label for="newPassword">New Password</label>
|
||||
<p-password id="newPassword" [(ngModel)]="newPassword" name="newPassword" [feedback]="false" required fluid></p-password>
|
||||
</div>
|
||||
|
||||
<div class="p-field">
|
||||
<label for="confirmNewPassword">Confirm New Password</label>
|
||||
<p-password id="confirmNewPassword" [(ngModel)]="confirmNewPassword" name="confirmNewPassword" [feedback]="false" required fluid></p-password>
|
||||
<p-message *ngIf="!passwordsMatch && confirmNewPassword" severity="error" text="New passwords do not match."></p-message>
|
||||
</div>
|
||||
|
||||
<p-button label="Change Password" icon="pi pi-key" (click)="changePassword()" class="p-fluid"></p-button>
|
||||
|
||||
<p-message *ngIf="errorMessage" severity="error" text="{{ errorMessage }}"></p-message>
|
||||
<p-message *ngIf="successMessage" severity="success" text="{{ successMessage }}"></p-message>
|
||||
</form>
|
||||
</ng-template>
|
||||
</p-card>
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,28 @@
|
||||
.change-password-container {
|
||||
@apply flex items-center justify-center min-h-screen bg-gradient-to-br from-blue-900 via-cyan-600 to-blue-400 relative;
|
||||
}
|
||||
|
||||
.change-password-wrapper {
|
||||
@apply flex flex-col items-center gap-6 absolute top-1/4 transform -translate-y-1/4;
|
||||
}
|
||||
|
||||
.app-title {
|
||||
@apply text-5xl font-extrabold text-white drop-shadow-lg;
|
||||
text-shadow: 0px 4px 6px rgba(0, 0, 0, 0.3);
|
||||
}
|
||||
|
||||
.change-password-card {
|
||||
@apply w-96 shadow-lg rounded-xl bg-opacity-90 backdrop-blur-lg;
|
||||
}
|
||||
|
||||
form {
|
||||
@apply flex flex-col gap-4;
|
||||
}
|
||||
|
||||
.p-field {
|
||||
@apply flex flex-col gap-2;
|
||||
}
|
||||
|
||||
p-button {
|
||||
@apply mt-4;
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
import {Component, inject} from '@angular/core';
|
||||
import { Button } from 'primeng/button';
|
||||
import { Card } from 'primeng/card';
|
||||
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
|
||||
import { Message } from 'primeng/message';
|
||||
import { NgIf } from '@angular/common';
|
||||
import { Password } from 'primeng/password';
|
||||
import {MessageService, PrimeTemplate} from 'primeng/api';
|
||||
import {UserService} from '../../../user.service';
|
||||
import {AuthService} from '../../service/auth.service';
|
||||
|
||||
@Component({
|
||||
selector: 'app-change-password',
|
||||
standalone: true,
|
||||
imports: [
|
||||
Button,
|
||||
Card,
|
||||
FormsModule,
|
||||
Message,
|
||||
NgIf,
|
||||
Password,
|
||||
PrimeTemplate,
|
||||
ReactiveFormsModule
|
||||
],
|
||||
templateUrl: './change-password.component.html',
|
||||
styleUrl: './change-password.component.scss'
|
||||
})
|
||||
export class ChangePasswordComponent {
|
||||
currentPassword: string = '';
|
||||
newPassword: string = '';
|
||||
confirmNewPassword: string = '';
|
||||
errorMessage: string | null = null;
|
||||
successMessage: string | null = null;
|
||||
|
||||
protected userService = inject(UserService);
|
||||
protected authService = inject(AuthService);
|
||||
protected messageService = inject(MessageService);
|
||||
|
||||
get passwordsMatch(): boolean {
|
||||
return this.newPassword === this.confirmNewPassword;
|
||||
}
|
||||
|
||||
changePassword() {
|
||||
this.errorMessage = null;
|
||||
this.successMessage = null;
|
||||
|
||||
if (!this.currentPassword || !this.newPassword || !this.confirmNewPassword) {
|
||||
this.errorMessage = 'All fields are required.';
|
||||
return;
|
||||
}
|
||||
|
||||
if (!this.passwordsMatch) {
|
||||
this.errorMessage = 'New passwords do not match.';
|
||||
return;
|
||||
}
|
||||
|
||||
this.userService.changePassword(this.currentPassword, this.newPassword).subscribe({
|
||||
next: () => {
|
||||
this.successMessage = 'Password changed successfully!';
|
||||
this.currentPassword = '';
|
||||
this.newPassword = '';
|
||||
this.confirmNewPassword = '';
|
||||
this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: 'Password Changed',
|
||||
detail: 'Your password has been changed successfully. Please log in again.'
|
||||
});
|
||||
this.logout();
|
||||
},
|
||||
error: (err) => {
|
||||
this.errorMessage = err.message;
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: 'Password Change Failed',
|
||||
detail: this.errorMessage ?? 'An unknown error occurred.'
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
logout() {
|
||||
this.authService.logout();
|
||||
window.location.href = '/login';
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Component } from '@angular/core';
|
||||
import {Component} from '@angular/core';
|
||||
import {AuthService} from '../../service/auth.service';
|
||||
import {Router} from '@angular/router';
|
||||
import {FormsModule} from '@angular/forms';
|
||||
@@ -30,12 +30,17 @@ export class LoginComponent {
|
||||
password = '';
|
||||
errorMessage = '';
|
||||
|
||||
constructor(private authService: AuthService, private router: Router) {}
|
||||
constructor(private authService: AuthService, private router: Router) {
|
||||
}
|
||||
|
||||
login(): void {
|
||||
this.authService.login({ username: this.username, password: this.password }).subscribe({
|
||||
next: () => {
|
||||
this.router.navigate(['/dashboard']);
|
||||
this.authService.login({username: this.username, password: this.password}).subscribe({
|
||||
next: (response) => {
|
||||
if (response.isDefaultPassword === 'true') {
|
||||
this.router.navigate(['/change-password']);
|
||||
} else {
|
||||
this.router.navigate(['/dashboard']);
|
||||
}
|
||||
},
|
||||
error: () => {
|
||||
this.errorMessage = 'Invalid username or password';
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
<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;">Change Password</th>
|
||||
<th style="width: 100px;">Delete</th>
|
||||
</tr>
|
||||
</ng-template>
|
||||
@@ -66,6 +67,11 @@
|
||||
[ngStyle]="{'visibility': 'hidden'}">
|
||||
</p-button>
|
||||
</td>
|
||||
<td class="text-center">
|
||||
<ng-container *ngIf="user.username !== 'admin'">
|
||||
<p-button icon="pi pi-key" outlined="true" severity="warn" (onClick)="openChangePasswordDialog(user)"></p-button>
|
||||
</ng-container>
|
||||
</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>
|
||||
@@ -74,4 +80,16 @@
|
||||
</tr>
|
||||
</ng-template>
|
||||
</p-table>
|
||||
|
||||
<p-dialog header="Change Password" [(visible)]="isPasswordDialogVisible" [modal]="true" [closable]="false" [style]="{width: '20vw'}">
|
||||
<div class="flex flex-col gap-8 items-center">
|
||||
<p-password [(ngModel)]="newPassword" placeholder="New Password" [feedback]="false" class="w-full" fluid></p-password>
|
||||
<p-password [(ngModel)]="confirmNewPassword" placeholder="Confirm Password" [feedback]="false" class="w-full" fluid></p-password>
|
||||
<p *ngIf="passwordError" class="p-error text-red-500 w-full text-left">{{ passwordError }}</p>
|
||||
<div class="flex gap-4 w-full justify-end">
|
||||
<p-button label="Cancel" icon="pi pi-times" severity="secondary" (onClick)="isPasswordDialogVisible = false"></p-button>
|
||||
<p-button label="Change" icon="pi pi-check" severity="success" (onClick)="submitPasswordChange()"></p-button>
|
||||
</div>
|
||||
</div>
|
||||
</p-dialog>
|
||||
</div>
|
||||
|
||||
@@ -11,10 +11,22 @@ import {Checkbox} from 'primeng/checkbox';
|
||||
import {MultiSelect} from 'primeng/multiselect';
|
||||
import {Library} from '../../../../book/model/library.model';
|
||||
import {LibraryService} from '../../../../book/service/library.service';
|
||||
import {Dialog} from 'primeng/dialog';
|
||||
import {Password} from 'primeng/password';
|
||||
|
||||
@Component({
|
||||
selector: 'app-admin',
|
||||
imports: [FormsModule, Button, TableModule, NgIf, Checkbox, NgStyle, MultiSelect],
|
||||
imports: [
|
||||
FormsModule,
|
||||
Button,
|
||||
TableModule,
|
||||
NgIf,
|
||||
Checkbox,
|
||||
NgStyle,
|
||||
MultiSelect,
|
||||
Dialog,
|
||||
Password,
|
||||
],
|
||||
templateUrl: './admin.component.html',
|
||||
styleUrls: ['./admin.component.scss'],
|
||||
})
|
||||
@@ -29,6 +41,12 @@ export class AdminComponent implements OnInit {
|
||||
editingLibraryIds: number[] = [];
|
||||
allLibraries: Library[] = [];
|
||||
|
||||
isPasswordDialogVisible = false;
|
||||
selectedUser: User | null = null;
|
||||
newPassword = '';
|
||||
confirmNewPassword = '';
|
||||
passwordError = '';
|
||||
|
||||
ngOnInit() {
|
||||
this.loadUsers();
|
||||
this.libraryService.getAllLibrariesFromAPI().subscribe({
|
||||
@@ -36,23 +54,32 @@ export class AdminComponent implements OnInit {
|
||||
this.allLibraries = libraries;
|
||||
},
|
||||
error: () => {
|
||||
this.messageService.add({severity: 'error', summary: 'Error', detail: 'Failed to load libraries'});
|
||||
}
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: 'Error',
|
||||
detail: 'Failed to load libraries',
|
||||
});
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
loadUsers() {
|
||||
this.userService.getUsers().subscribe({
|
||||
next: (data) => {
|
||||
this.users = data.map(user => ({
|
||||
this.users = data.map((user) => ({
|
||||
...user,
|
||||
isEditing: false,
|
||||
selectedLibraryIds: user.assignedLibraries?.map(lib => lib.id) || [],
|
||||
libraryNames: user.assignedLibraries?.map(lib => lib.name).join(', ') || ''
|
||||
selectedLibraryIds: user.assignedLibraries?.map((lib) => lib.id) || [],
|
||||
libraryNames:
|
||||
user.assignedLibraries?.map((lib) => lib.name).join(', ') || '',
|
||||
}));
|
||||
},
|
||||
error: () => {
|
||||
this.messageService.add({severity: 'error', summary: 'Error', detail: 'Failed to fetch users'});
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: 'Error',
|
||||
detail: 'Failed to fetch users',
|
||||
});
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -76,44 +103,101 @@ export class AdminComponent implements OnInit {
|
||||
if (user.isEditing) {
|
||||
this.editingLibraryIds = [...user.selectedLibraryIds];
|
||||
} else {
|
||||
user.libraryNames = user.assignedLibraries?.map((lib: Library) => lib.name).join(', ') || '';
|
||||
user.libraryNames =
|
||||
user.assignedLibraries
|
||||
?.map((lib: Library) => lib.name)
|
||||
.join(', ') || '';
|
||||
}
|
||||
}
|
||||
|
||||
saveUser(user: any) {
|
||||
user.selectedLibraryIds = [...this.editingLibraryIds];
|
||||
this.userService.updateUser(user.id, {
|
||||
name: user.name,
|
||||
email: user.email,
|
||||
permissions: user.permissions,
|
||||
assignedLibraries: user.selectedLibraryIds
|
||||
}).subscribe({
|
||||
next: () => {
|
||||
user.isEditing = false;
|
||||
this.loadUsers();
|
||||
this.messageService.add({severity: 'success', summary: 'Success', detail: 'User updated successfully'});
|
||||
},
|
||||
error: () => {
|
||||
this.messageService.add({severity: 'error', summary: 'Error', detail: 'Failed to update user'});
|
||||
},
|
||||
});
|
||||
this.userService
|
||||
.updateUser(user.id, {
|
||||
name: user.name,
|
||||
email: user.email,
|
||||
permissions: user.permissions,
|
||||
assignedLibraries: user.selectedLibraryIds,
|
||||
})
|
||||
.subscribe({
|
||||
next: () => {
|
||||
user.isEditing = false;
|
||||
this.loadUsers();
|
||||
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.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}`,
|
||||
detail:
|
||||
err.error?.message ||
|
||||
`Failed to delete user ${user.username}`,
|
||||
});
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
openChangePasswordDialog(user: User) {
|
||||
this.selectedUser = user;
|
||||
this.newPassword = '';
|
||||
this.confirmNewPassword = '';
|
||||
this.passwordError = '';
|
||||
this.isPasswordDialogVisible = true;
|
||||
}
|
||||
|
||||
submitPasswordChange() {
|
||||
if (!this.newPassword || !this.confirmNewPassword) {
|
||||
this.passwordError = 'Both fields are required';
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.newPassword !== this.confirmNewPassword) {
|
||||
this.passwordError = 'Passwords do not match';
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.selectedUser) {
|
||||
this.userService
|
||||
.changeUserPassword(this.selectedUser.id, this.newPassword)
|
||||
.subscribe({
|
||||
next: () => {
|
||||
this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: 'Success',
|
||||
detail: 'Password changed successfully',
|
||||
});
|
||||
this.isPasswordDialogVisible = false;
|
||||
},
|
||||
error: (err) => {
|
||||
this.passwordError = err;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+3
-3
@@ -52,17 +52,17 @@
|
||||
<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 formControlName="canUpload" [binary]="true"></p-checkbox>
|
||||
<p-checkbox formControlName="permissionUpload" [binary]="true"></p-checkbox>
|
||||
<label>Upload Books</label>
|
||||
</div>
|
||||
|
||||
<div class="flex items-center gap-2">
|
||||
<p-checkbox formControlName="canDownload" [binary]="true"></p-checkbox>
|
||||
<p-checkbox formControlName="permissionDownload" [binary]="true"></p-checkbox>
|
||||
<label>Download Books</label>
|
||||
</div>
|
||||
|
||||
<div class="flex items-center gap-2">
|
||||
<p-checkbox formControlName="canEditMetadata" [binary]="true"></p-checkbox>
|
||||
<p-checkbox formControlName="permissionEditMetadata" [binary]="true"></p-checkbox>
|
||||
<label>Edit Metadata</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
+3
-3
@@ -45,9 +45,9 @@ export class CreateUserDialogComponent implements OnInit {
|
||||
username: ['', Validators.required],
|
||||
password: ['', [Validators.required, Validators.minLength(6)]],
|
||||
selectedLibraries: [[], Validators.required],
|
||||
canUpload: [false],
|
||||
canDownload: [false],
|
||||
canEditMetadata: [false]
|
||||
permissionUpload: [false],
|
||||
permissionDownload: [false],
|
||||
permissionEditMetadata: [false]
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
<p-tab value="1">Quick Metadata</p-tab>
|
||||
</ng-container>
|
||||
<ng-container *ngIf="userData.permissions.admin">
|
||||
<p-tab value="2">Admin Panel</p-tab>
|
||||
<p-tab value="2">User Management</p-tab>
|
||||
</ng-container>
|
||||
</p-tablist>
|
||||
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import {inject, Injectable, Injector} from '@angular/core';
|
||||
import {HttpClient} from '@angular/common/http';
|
||||
import {BehaviorSubject, Observable, of} from 'rxjs';
|
||||
import {BehaviorSubject, Observable, of, throwError} from 'rxjs';
|
||||
import {API_CONFIG} from './config/api-config';
|
||||
import {jwtDecode} from 'jwt-decode';
|
||||
import {RxStompService} from './shared/websocket/rx-stomp.service';
|
||||
import {Library} from './book/model/library.model';
|
||||
import {catchError} from 'rxjs/operators';
|
||||
|
||||
export interface User {
|
||||
id: number;
|
||||
@@ -60,19 +61,7 @@ export class UserService {
|
||||
userData$ = this.userDataSubject.asObservable();
|
||||
|
||||
constructor() {
|
||||
this.loadUserFromToken();
|
||||
}
|
||||
|
||||
private loadUserFromToken(): void {
|
||||
const token = localStorage.getItem('accessToken');
|
||||
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.getMyself().subscribe(user => {
|
||||
this.userDataSubject.next(user);
|
||||
this.startWebSocket();
|
||||
});
|
||||
@@ -102,6 +91,32 @@ export class UserService {
|
||||
return this.http.delete<void>(`${this.userUrl}/${userId}`);
|
||||
}
|
||||
|
||||
changeUserPassword(userId: number, newPassword: string): Observable<void> {
|
||||
const payload = {
|
||||
userId: userId,
|
||||
newPassword: newPassword
|
||||
};
|
||||
return this.http.put<void>(`${this.userUrl}/change-user-password`, payload).pipe(
|
||||
catchError((error) => {
|
||||
const errorMessage = error?.error?.message || 'An unexpected error occurred. Please try again.';
|
||||
return throwError(() => new Error(errorMessage));
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
changePassword(currentPassword: string, newPassword: string): Observable<void> {
|
||||
const payload = {
|
||||
currentPassword: currentPassword,
|
||||
newPassword: newPassword
|
||||
};
|
||||
return this.http.put<void>(`${this.userUrl}/change-password`, payload).pipe(
|
||||
catchError((error) => {
|
||||
const errorMessage = error?.error?.message || 'An unexpected error occurred. Please try again.';
|
||||
return throwError(() => new Error(errorMessage));
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
updateBookPreferences(userId: number, prefs: UserBookPreferences): void {
|
||||
this.http.put<void>(`${this.userUrl}/${userId}/book-preferences`, prefs)
|
||||
.subscribe(() => {
|
||||
|
||||
Reference in New Issue
Block a user