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);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user