- 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,
|
||||
|
||||
Reference in New Issue
Block a user